package com.zsy.srpingframework.beans.factory.support;

import com.zsy.srpingframework.beans.factory.beanfactory.DefalutSingletonBeanRegistry;
import com.zsy.srpingframework.beans.factory.config.BeanDefinition;
import com.zsy.srpingframework.beans.factory.exception.BeansException;
import com.zsy.srpingframework.beans.factory.jiekou.BeanFactory;

public abstract class AbstractBeanFactory extends DefalutSingletonBeanRegistry implements BeanFactory {
    @Override
    public Object getBean(String name) throws BeansException {
        return doGetBean(name,null);
    }

    @Override
    public Object getBean(String name, Object... args) throws BeansException {
        return doGetBean(name, args);
    }

    @Override
    public <T> T getBean(String name, Class<T> reqquiredType) throws BeansException {
        return (T) getBean(name);
    }


    protected <T> T doGetBean(String name, final Object[] args) {
        Object singleton = getSingleton(name);
        if (singleton != null) {
            return (T) singleton;
        }
        BeanDefinition beanDefinition = getBeanDefinition(name);
        return (T) createBean(name, beanDefinition, args);
    }

    protected abstract Object createBean(String name, BeanDefinition beanDefinition, Object[] args);

    protected abstract BeanDefinition getBeanDefinition(String name);
}
